import {
  Component,
  Input,
  OnInit,
  Inject,
  forwardRef,
  ViewChild,
  ElementRef,
} from "@angular/core";

import { IonSegment } from "@ionic/angular";

import { ComItem } from "../../route/entry/com-item";
import { EventService } from "../../shared/service/event.service";
import { HttpService } from "../../shared/service/http.service";
import { AppGlobalService } from "../../shared/service/app-global.service";

@Component({
  selector: "app-button-nav-three",
  templateUrl: "./button-nav-three.component.html",
  styleUrls: ["./button-nav-three.component.scss"],
})
export class ButtonNavThreeComponent implements OnInit {
  @ViewChild("segment", { read: ElementRef }) private segment: ElementRef;
  @ViewChild("segment", null) ionSegment: IonSegment;
  receiverTag = "ButtonNavThreeComponentReceiver";
  subComs5: ComItem[];
  @Input() tagData: any;
  aWidth: string;
  isSelected: boolean;
  currentClickObj: any;
  currentCLickIndexTab: any;
  isRootURL: any; // 用于检查URL是否有变化
  selectedSegment = 0;
  isAutoFillData: undefined;
  constructor(
    private eventService: EventService,
    private httpService: HttpService,
    private appGlobalService: AppGlobalService
  ) {
    if (this.eventService.eventEmit.listenerCount(this.receiverTag) > 0) {
      this.eventService.eventEmit.removeListener(this.receiverTag);
    }
    this.eventService.eventEmit.on(this.receiverTag, (res) => {
      if (localStorage.getItem(this.receiverTag + "Tag")) {
        localStorage.removeItem(this.receiverTag + "Tag");
        this.subComs5 = res.coms;
      }
    });
  }

  async segmentChanged(e: any) {
    try {
      this.eventService.removeCustomListListeners();
      const index = e.detail.value;
      const segmentButton = this.segment.nativeElement.children[index];
      segmentButton.scrollIntoView({
        behavior: "smooth",
        inline: "center",
        block: "nearest",
      });
      await this.showIndicator();
      if (this.tagData.data) {
        this.httpService.post(
          "application/part",
          {
            viewId: this.tagData.data[index].partLink.target,
            sessionId: localStorage.getItem("sessionId"),
            params: this.tagData.data[index].partLink.params,
          },
          (res: any) => {
            if (res) {
              const tmpData = JSON.parse(res.script);
              if (this.isAutoFillData && this.isAutoFillData === true) {
                tmpData.tags[0].isAutoFillData = true;
              }
              // 发送事件
              const eventEmitObj = {
                data: tmpData,
                receiverTag: this.receiverTag,
              };
              localStorage.setItem(
                "generatedComItemWithBufferTag",
                JSON.stringify(eventEmitObj)
              );
              this.eventService.eventEmit.emit(
                "generatedComItemWithBuffer",
                ""
              );
            }
          }
        );
      }
    } catch (error) {
      console.log("error----->" + JSON.stringify(error));
    }
  }

  showIndicator() {
    const len = this.tagData.data.length;
    // for (let i = 0; i < len; i++) {
    //     document.getElementById('segmentIndicator' + i).style.display = "none";
    // }

    // bug: #574 切换tab页后应从当前tab的第一条信息开始展示
    const contents = document.querySelectorAll("ion-content");
    const ele = document.querySelector("ion-content #scrollContent");
    let target = null;
    contents.forEach((item) => {
      if (this.isChildOf(ele, item)) {
        target = item;
      }
    });
    target.getScrollElement().then((e) => {
      if (e.scrollTop >= document.getElementById("scrollContent").offsetTop) {
        target.scrollToPoint(
          0,
          document.getElementById("scrollContent").offsetTop + 44
        );
      }
    });
  }
  /**
   * 判断是否子节点
   * @param child 子节点
   * @param parent 父节点
   */
  isChildOf(child, parent) {
    let parentNode;
    if (child && parent) {
      parentNode = child.parentNode;
      while (parentNode) {
        if (parent === parentNode) {
          return true;
        }
        parentNode = parentNode.parentNode;
      }
    }
    return false;
  }
  async ngOnInit() {
    try {
      this.eventService.removeCustomListListeners();
      this.isAutoFillData = undefined;
      const that = this;
      this.aWidth = 100 / this.tagData.data.length + "%";
      const cDataObj = this.tagData.currentData;
      this.selectedSegment = +this.tagData.currentTab;
      if (cDataObj !== undefined) {
        const tags = cDataObj.tags;
        if (tags !== undefined && tags.length > 0) {
          that.httpService.post(
            "application/part",
            {
              viewId: this.tagData.data[0].partLink.target,
              sessionId: localStorage.getItem("sessionId"),
              params: this.tagData.data[0].partLink.params,
            },
            (res: any) => {
              if (res) {
                const tmpData = JSON.parse(res.script);
                if (
                  cDataObj.tags[0] &&
                  cDataObj.tags[0].isAutoFillData !== undefined
                ) {
                  tmpData.tags[0].isAutoFillData =
                    cDataObj.tags[0].isAutoFillData;
                  this.isAutoFillData = cDataObj.tags[0].isAutoFillData;
                }
                // #task-view-916
                if (this.tagData.refresh) {
                  tmpData.isPullToRefresh = this.tagData.refresh;
                }
                // tmpData.isPullToRefresh = true;
                // 发送事件
                const eventEmitObj = {
                  data: tmpData,
                  receiverTag: this.receiverTag,
                };
                localStorage.setItem(
                  "generatedComItemWithBufferTag",
                  JSON.stringify(eventEmitObj)
                );
                this.eventService.eventEmit.emit(
                  "generatedComItemWithBuffer",
                  ""
                );
              }
            }
          );
        }
      }
    } catch (error) {
      console.log("error----->" + JSON.stringify(error));
    }
  }

  get(obj) {
    let target;
    let subParams;
    if (obj.partLink) {
      target = obj.partLink.target;
      subParams = obj.partlink.params;
    } else if (obj.link) {
      target = obj.link.target;
      subParams = obj.link.params;
    } else {
      return;
    }
    const params = {
      pageId: target,
      params: subParams,
      sessionId: localStorage.getItem("sessionId"),
    };
    this.appGlobalService.goToForward(params);
  }

  getCustomNgStyle(cssType) {
    if (cssType !== undefined && cssType === 3) {
      return {
        flex: "unset"
      };
    }
  }
}
